<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div>
                <div ref="ganttRef" :style="'height:' + (tabHeight - 80) + 'px'"></div>
            </div>

            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import { gantt } from 'dhtmlx-gantt'
    import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'

    const tabHeight = ref(0)
    const tasks = ref({
        data: [
            {
                id: 1,
                text: '内部系统2023W22-23',
                start_date: '2024-10-11 00:00',
                duration: 5,
                progress: 0,
                status: 'default',
                open: true,
                type: 'father',
                milepostName: '项目阶段项目阶段项目阶段项目阶段项目阶段'
            },
            {
                id: 11,
                text: '计划进展',
                start_date: '2024-11-01 00:00',
                duration: 20,
                progress: 0,
                status: 'plan',
                parent: '1',
                type: 'son'
            },
            {
                id: 12,
                text: '实际进展',
                start_date: '2024-11-01 00:00',
                duration: 4,
                progress: 0,
                status: 'delay',
                parent: '1',
                type: 'son'
            },
            {
                id: 2,
                text: '内部系统2023W22-23',
                start_date: '2024-9-11 00:00',
                duration: 99,
                progress: 0,
                status: 'default',
                open: true,
                type: 'father'
            },
            {
                id: 21,
                text: '计划进展',
                start_date: '2024-9-01 00:00',
                duration: 290,
                progress: 0,
                status: 'plan',
                parent: '2',
                type: 'son'
            },
            {
                id: 22,
                text: '实际进展',
                start_date: '2024-7-01 00:00',
                duration: 128,
                progress: 0,
                status: 'delay',
                parent: '2',
                type: 'son'
            }
        ]
    })
    const onTaskDblClick = ref(null)

    const generateData = num => {
        const data = []

        for (let i = 1; i <= num; i++) {
            const startDate = new Date(new Date().setDate(new Date().getDate() + Math.floor(Math.random() * 30))) // 随机开始时间，30天内
            const duration = Math.floor(Math.random() * 100) + 10 // 随机持续时间，最少10天
            const parentId = i * 10
            const status2 = Math.random() > 0.5 ? 'default' : 'delay' // 第二条子任务status随机

            // 父任务
            data.push({
                id: parentId,
                projectName: `内部系统2023W${Math.floor(Math.random() * 50) + 1}`,
                start_date: startDate.toISOString().slice(0, 19).replace('T', ' '),
                duration: duration,
                progress: 0,
                status: 'default',
                open: true,
                type: 'father',
                milepostName: '项目阶段项目阶段项目阶段项目阶段项目阶段'
            })

            // 第一个子任务
            data.push({
                id: parentId + 1,
                projectName: '计划进展',
                start_date: new Date(startDate.getTime() + Math.random() * 86400000)
                    .toISOString()
                    .slice(0, 19)
                    .replace('T', ' '), // 子任务start_date随机
                duration: Math.floor(Math.random() * 100) + 5,
                progress: 0,
                status: 'plan',
                parent: parentId,
                type: 'son'
            })

            // 第二个子任务
            data.push({
                id: parentId + 2,
                projectName: '实际进展',
                start_date: new Date(startDate.getTime() + Math.random() * 86400000)
                    .toISOString()
                    .slice(0, 19)
                    .replace('T', ' '),
                duration: Math.floor(Math.random() * 100) + 5,
                progress: 0,
                status: status2, // 随机生成default或delay
                parent: parentId,
                type: 'son'
            })
        }

        return data
    }

    // tasks.value.data = generateData(1000) // 生成100组数据
    tasks.value.data = [ {
      "id": 10,
      "projectName": "内部系统2023W37",
      "start_date": "2025-01-31",
      "duration": 33,
      "progress": 0,
      "status": "default",
      "open": true,
      "type": "father",
      "milepostName": "项目阶段项目阶段项目阶段项目阶段项目阶段",
      "end_date": "2025-03-05",
      "$no_start": false,
      "$no_end": false,
      "$rendered_type": "task",
      "$calculate_duration": true,
      "$effective_calendar": "global",
      "$source": [],
      "$target": [],
      "parent": 0,
      "$rendered_parent": 0,
      "$level": 0,
      "$local_index": 0,
      "$open": true,
      "$expanded_branch": true,
      "$resourceAssignments": [],
      "$index": 0
    },
      {
        "id": 11,
        "projectName": "计划进展",
        "start_date": "2025-01-31",
        "duration": 59,
        "progress": 0,
        "status": "plan",
        "parent": 10,
        "type": "son",
        "end_date": "2025-03-31",
        "$no_start": false,
        "$no_end": false,
        "$rendered_type": "task",
        "$calculate_duration": true,
        "$effective_calendar": "global",
        "$source": [],
        "$target": [],
        "$rendered_parent": 10,
        "$level": 1,
        "$local_index": 0,
        "$open": false,
        "$expanded_branch": true,
        "$resourceAssignments": [],
        "$index": 1
      },
      {
        "id": 12,
        "projectName": "实际进展",
        "start_date": "2025-02-01",
        "duration": 23,
        "progress": 0,
        "status": "delay",
        "parent": 10,
        "type": "son",
        "end_date": "2025-02-24",
        "$no_start": false,
        "$no_end": false,
        "$rendered_type": "task",
        "$calculate_duration": true,
        "$effective_calendar": "global",
        "$source": [],
        "$target": [],
        "$rendered_parent": 10,
        "$level": 1,
        "$local_index": 1,
        "$open": false,
        "$expanded_branch": true,
        "$resourceAssignments": [],
        "$index": 2
      }]
    console.log(tasks.value.data);
    // 初始化
    const init = () => {
        gantt.i18n.setLocale('cn') // 汉化 - 默认是英文
        gantt.locale.date = {
            month_full: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            month_short: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            day_full: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
            day_short: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        }

        gantt.locale.labels = {
            dhx_cal_today_button: '今天',
            day_tab: '日',
            week_tab: '周',
            month_tab: '月',
            new_event: '新建日程',
            icon_save: '保存',
            icon_cancel: '关闭',
            icon_details: '详细',
            icon_edit: '编辑',
            icon_delete: '删除',
            confirm_closing: '请确认是否撤销修改!',
            confirm_deleting: '是否删除计划?',
            section_description: '描述:',
            section_time: '时间范围:',
            section_type: '类型:',
            section_text: '计划名称:',
            section_test: '测试:',
            section_projectClass: '项目类型:',
            taskProjectType_0: '项目任务',
            taskProjectType_1: '普通任务',
            section_head: '负责人:',
            section_priority: '优先级:',
            taskProgress: '任务状态',
            taskProgress_0: '未开始',
            taskProgress_1: '进行中',
            taskProgress_2: '已完成',
            taskProgress_3: '已延期',
            taskProgress_4: '搁置中',
            section_template: 'Details',
            column_text: '计划名称',
            column_start_date: '开始时间',
            column_duration: '持续时间',
            column_add: '',
            column_priority: '难度'
        }

        // 自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
        gantt.config.autosize = false
        gantt.config.readonly = true
        gantt.config.show_grid = true
        gantt.config.scale_height = 50
        gantt.config.bar_height = 26
        gantt.config.row_height = 32
        // gantt.config.min_column_width = 32
        // gantt.config.min_grid_column_width = 32
        gantt.config.xml_date = '%Y-%m-%d %H:%i'
      console.log(gantt.config);
        gantt.config.columns = [
            {
                name: 'projectName',
                label: '项目名称',
                tree: true,
                width: '200',
                align: 'left',
                template: function (task) {
                    return `<div class="omit-div-project" title="${task.projectName}">${task.projectName}</div>`
                }
            },
            {
                label: '项目阶段',
                width: '100',
                align: 'center',
                name: 'milepostName',
                template: function (task) {
                    return `<div class="omit-div" title="${task.milepostName}">${task.milepostName}</div>`
                }
            },
            {
                label: '任务名称',
                width: '100',

                align: 'center',
                name: 'taskName'
            },
            {
                label: '任务状态',
                width: '100',

                align: 'center',
                name: 'taskStatus'
            },
            {
                label: '计划开始时间',
                width: '100',

                align: 'center',
                name: 'startTime'
            },
            {
                label: '计划结束时间',
                width: '100',

                align: 'center',
                name: 'endTime'
            },
            {
                label: '任务负责人',
                width: '100',

                align: 'center',
                name: 'taskOwer'
            }
        ]
        // timeLine 文字
        gantt.templates.task_text = function (start, end, task) {
            return ''
        }

        gantt.templates.task_class = function (start, end, item) {
            if (item.type === 'father') {
                return 'no-show'
            }
            switch (item.status) {
                case 'delay':
                    return 'gantt_begined'
                case 'default':
                    return 'gantt_success'
                case 'plan':
                    return 'gantt_plan'
                default:
                    return 'gantt_success'
            }
        }

        gantt.config.fit_tasks = true
        gantt.config.drag_project = true

        if (props.dateType === 'year') {
            gantt.config.scales = [{ unit: 'year', step: 1, date: ' %Y 年' }]
        } else if (props.dateType === 'month') {
            gantt.config.scales = [
                { unit: 'year', step: 1, date: ' %Y 年' },
                { unit: 'month', step: 1, date: '%F' }
            ]
        } else {
            gantt.config.scales = [
                { unit: 'month', step: 1, date: ' %Y 年  %F' },
                { unit: 'day', step: 1, date: '%d' }
            ]
        }

        gantt.config.lightbox.sections = [
            { name: 'description', height: 70, map_to: 'text', type: 'textarea', focus: true },
            { name: 'type', type: 'typeselect', map_to: 'type' },
            { name: 'time', type: 'duration', map_to: 'auto' }
        ]

        if (onTaskDblClick.value) gantt.detachEvent(onTaskDblClick.value)
        onTaskDblClick.value = gantt.attachEvent('onTaskDblClick', (id, e) => {
            // Emit the double click event
            return true
        })

        gantt.clearAll()
        gantt.init(ganttRef.value)
      console.log(tasks.value);
        gantt.parse(tasks.value)
    }

    // 页面初始化
    onMounted(() => {
        const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
        tabHeight.value = h - 120
        init()
    })

    const ganttRef = ref(null)
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    :deep(.gantt_row.gantt_row_project:hover) {
        background: #e4e4e4 !important;
    }

    :deep(.gantt_row.gantt_row_task:hover) {
        background: #e4e4e4 !important;
    }
    :deep(.gantt_begined) {
        background-color: #fc4c29;
        border: #fc4c29;
    }
    :deep(.gantt_success) {
        background-color: #c7f870;
        border: #c7f870;
    }
    :deep(.gantt_plan) {
        background-color: #ffe58f;
        border: #ffe58f;
    }
    :deep(.no-show) {
        display: none;
    }
    /*
    :deep(.gantt_row) {
        height: 24px !important;
    }
    :deep(.gantt_tree_content) {
        line-height: 24px;
    }
    :deep(.gantt_task_line) {
      height: 12px !important;
    }
    :deep(.gantt_task_row) {
        height: 24px !important;
        line-height: 24px;
    }
    :deep(.gantt_task_progress_wrapper) {
        height: 12px !important;
    }
    */
    :deep(.gantt_file) {
        display: none;
    }
    :deep(.gantt_folder_open) {
        display: none;
    }
    :deep(.gantt_grid_data .gantt_cell) {
        border-right: 1px solid #d9d9d9;
    }

    :deep(.omit-div) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }
    :deep(.omit-div-project) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 150px;
    }
    :deep(.gantt_blank) {
        display: none;
    }
</style>
